package or.exa.cangguan.service.impl;

import lombok.extern.slf4j.Slf4j;
import or.exa.cangguan.common.Redis;
import or.exa.cangguan.mapper.PermissionMapper;
import or.exa.cangguan.mapper.RolePermissionMapper;
import or.exa.cangguan.mapper.UserInfoMapper;
import or.exa.cangguan.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private Redis redis;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;




    //通过用户id返回权限列表
    @Override
    public List<String> getPermission(String userName) {
        Integer roleId = userInfoMapper.selectRoleIdByUsername(userName);
        log.info("权限id: {}", roleId);

        Object o = redis.get("permission:" + roleId);
        if(o !=null){
            return (List<String>) o;
        }

        List<String> permissions=new ArrayList<>();
        List<Integer> integers = rolePermissionMapper.selectByRoleId(roleId);
        log.info("权限id: {}", integers);
        for (Integer integer : integers) {
            String permissionById = permissionMapper.selectPermissionById(integer);
            permissions.add(permissionById);
        }
        log.info("权限: {}", permissions);
        redis.set("permission:" + roleId, permissions);

        return permissions;
    }



}
